package com.concurrency.example.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;

/**
 * 统一时刻最多两个线程访问的锁
 * state表示可以使用的资源数
 */
public class TwinsLock implements Lock {
    private static class Sync extends AbstractQueuedSynchronizer {

        public Sync(int count) {
            if (count < 0) {
                throw new IllegalArgumentException("参数不能小于0");
            }
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int reduceCount) {
            for (; ; ) {
                int current = getState();
                int newCount = current - reduceCount;
                //如果资源数小于0不在获取，直接返回
                //否则更新资源数
                if (newCount < 0 || compareAndSetState(current, newCount)) {
                    return newCount;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int addCount) {
            for (; ; ) {
                int current = getState();
                int newCount = current + addCount;
                if (compareAndSetState(current, newCount)) {
                    return true;
                }
            }
        }
    }

    private static final Sync sync = new Sync(2);
    @Override
    public void lock() {
        sync.acquireShared(1);
    }
    @Override
    public void unlock() {
        sync.releaseShared(1);
    }


    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

}
